package cn.ad.server.web.spring.service.httpclient4;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Arrays;

/**
 * 此类和 java.io.ByteArrayOutputStream大部分代码一致。
 * 注意：非线程安全类。
 * 
 * @see ByteArrayOutputStream
 * @author wangwei
 *
 */
public class ByteArrayWrapStream extends OutputStream {

     private byte buf[];

     private int count;

    public ByteArrayWrapStream() {
        this(32);
    }

    public ByteArrayWrapStream(int size) {
        if (size < 0) {
            throw new IllegalArgumentException("Negative initial size: "
                                               + size);
        }
        buf = new byte[size];
    }

    private void ensureCapacity(int minCapacity) {
        // overflow-conscious code
        if (minCapacity - buf.length > 0)
            grow(minCapacity);
    }

    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = buf.length;
        int newCapacity = oldCapacity << 1;
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity < 0) {
            if (minCapacity < 0) // overflow
                throw new OutOfMemoryError();
            newCapacity = Integer.MAX_VALUE;
        }
        buf = Arrays.copyOf(buf, newCapacity);
    }

    public synchronized void write(int b) {
        ensureCapacity(count + 1);
        buf[count] = (byte) b;
        count += 1;
    }

    public synchronized void write(byte b[], int off, int len) {
        if ((off < 0) || (off > b.length) || (len < 0) ||
            ((off + len) - b.length > 0)) {
            throw new IndexOutOfBoundsException();
        }
        ensureCapacity(count + len);
        System.arraycopy(b, off, buf, count, len);
        count += len;
    }

    public synchronized void writeTo(OutputStream out) throws IOException {
        out.write(buf, 0, count);
    }

    public synchronized void reset() {
        count = 0;
    }

    public synchronized byte toByteArray()[] {
        return Arrays.copyOf(buf, count);
    }

    public synchronized int size() {
        return count;
    }

    public synchronized String toString() {
        return new String(buf, 0, count);
    }

    public synchronized String toString(String charsetName)
        throws UnsupportedEncodingException
    {
        return new String(buf, 0, count, charsetName);
    }

    public void close() throws IOException {
    }
    
    /**
     * 生成ByteArrayInputStream对象。
     * 注意：非线程安全类。ByteArrayInputStream和此ByteArrayWrapStream共享原始数据buffer
     * @return ByteArrayInputStream
     * @throws Exception
     */
    public ByteArrayInputStream generateInputStream()
    {
        ByteArrayInputStream swapStream = new ByteArrayInputStream(this.buf);
        return swapStream;
    }
    
    /**
     * 返回String
     * @param charset
     * @return
     */
    public String toString(Charset charset){
    	return new String(this.buf, charset);
    }
    
    
	
}
